<?php

namespace App\Models\Cruise;

use App\Models\BaseModel;
use App\Service\BaseService;
use Illuminate\Support\Facades\Cache;

class CruiseCheckRiskProblemModel extends BaseModel
{
    protected $table    = 'cruise_check_risk_problem';
    protected $fillable = [
        'problemName',
        'riskType1',
        'riskName1',
        'riskType2',
        'riskName2',
        'riskExplain2',
        'status',
        'otherType',
        'createdAt',
    ];

    public $timestamps = false;

    const STATUS_SHOW = 1; // 显示
    const STATUS_HIDE = 0; // 隐藏

    public function riskType2ToProblems()
    {
        return $this->hasMany(CruiseCheckRiskProblemModel::class, 'riskType2', 'riskType2');
    }

    public static function riskType2Problems(int $riskType1): array
    {
        return Cache::remember("riskType2Problems6:{$riskType1}", 1200, function () use ($riskType1) {

            // 二级列表
            return CruiseCheckRiskProblemModel
                ::query()
                ->with('riskType2ToProblems')
                ->where('riskType1', $riskType1)
                ->groupBy('riskType2')
                ->select('riskType2', 'riskName2', 'otherType', 'riskExplain2')
                ->get()->map(function ($item) {
                    return [
                        'riskType2' => $item['riskType2'],
                        'riskName2' => $item['riskName2'],
                        'otherType' => $item['otherType'],
                        'riskExplain2' => $item['riskExplain2'],
                        'problems'  => $item->riskType2ToProblems->map(function ($item) {
                            return [
                                'id'          => $item['id'],
                                'problemName' => $item['problemName'],
                                'status'      => $item['status'],
                            ];
                        }),
                    ];
                })->toArray();
        });
    }

    /**
     * 获取名称
     * @param string $column
     * @param int $id
     * @return string
     */
    public static function getName(string $column, int $id): string
    {
        $mappings = Cache::store('array')->remember("CruiseCheckRiskProblemGetName:{$column}", 1200, function () use ($column) {

            switch ($column) {
                case 'riskName1':
                    $mappings = self::query()->distinct()->pluck('riskName1', 'riskType1');
                    break;
                case 'riskName2':
                    $mappings = self::query()->distinct()->pluck('riskName2', 'riskType2');
                    break;
                case 'problemName':
                    $mappings = self::query()->pluck('problemName', 'id');
                    break;
                default:
                    BaseService::throwErr('不支持的column');
            }

            return $mappings;
        });

        return $mappings[$id] ?? '';
    }
}
